<template>
  <div class="scene-project-box">
    <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
      <template v-for="(item, index) in formList">
        <el-form-item
          :key="`${item.prop}${index}`"
          :style="item.itemStyle || {}"
          :label="item.name"
          :prop="item.prop"
          :class="item.itemClass"
        >
          <component
            :is="item.componentType || 'el-input'"
            :style="item.style || {}"
            :value-format="item.valueFormat || {}"
            v-if="item.prop"
            v-model="formData[item.prop]"
            :clearable="true"
            :class="item.class"
            v-bind="item.attrConfig || {}"
            @change="handlerSelectData(item)"
          >
            <template v-for="option in item.optionList">
              <el-option
                :key="option.code"
                :label="option.name"
                :value="option.code"
              />
            </template>
          </component>
        </el-form-item>
      </template>
      <el-row>
        <el-col :span="24">
          <el-form-item label="项目图片">
            <el-upload
              ref="upload"
              list-type="picture-card"
              action=""
              :on-change="handleChange"
              :on-remove="handleRemove"
              :file-list="fileList"
              :auto-upload="false"
              :limit="9"
              accept="image/*"
            >
              <i class="el-icon-plus" />
              <div slot="tip" class="el-upload__tip">
                <span>图片不超过9张，请上传jpg/png文件，且不超过5MB,建议尺寸500px * 100px </span>
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="背景图">
            <el-upload
              ref="upload"
              list-type="picture-card"
              action=""
              :on-change="handleBackgroundChange"
              :on-remove="handleBackgroundRemove"
              :file-list="backgroundList"
              :auto-upload="false"
              :limit="1"
              accept="image/*"
            >
              <i class="el-icon-plus" />
              <div slot="tip" class="el-upload__tip">
                <span>请上传jpg/png文件，且不超过5MB,建议尺寸1800px * 900px</span>
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="项目介绍" prop="proRemark">
            <WangEditor v-model="this.formData.proRemark" @editorChange="editorChange"
                        :default-value="this.formData.proRemark" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { dictMixin } from '@/mixin/dict'
import WangEditor from '@/components/WangEditor/index.vue'

export default {
  name: 'AddSceneProject',
  components: { WangEditor },
  mixins: [dictMixin],
  props: {
    // 请求参数
    requestParams: {
      type: Object,
      default: () => ({})
    },
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: [],
      backgroundList: [],
      isAdd: true,
      formData: {},
      maxRemarkLength: 200,
      formList: [
        {
          name: '项目id',
          prop: 'id',
          attrConfig: {
            disabled: true
          }
        }, {
          name: '项目名称',
          prop: 'projectName',
          attrConfig: { placeholder: '请输入项目名称' }
        },
        {
          name: '交付时间',
          prop: 'deliverTime',
          attrConfig: { placeholder: '年-月-日' },
          componentType: 'el-date-picker',
          valueFormat: 'yyyy-MM-dd',
          style: { width: '100%' }
        },
        {
          name: '项目地点',
          prop: 'address',
          attrConfig: { placeholder: '请输入项目地点' }
        },
        {
          name: '总用地面积(m²)',
          prop: 'landArea',
          attrConfig: { placeholder: '请输入总用地面积(m²)' }
        },
        {
          name: '总建筑面积(m²)',
          prop: 'floorArea',
          attrConfig: { placeholder: '请输入总建筑面积(m²)' }
        },
        {
          name: '项目负责人',
          prop: 'userId',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'UserSelected'
          },
          attrConfig: {
            placeholder: '请选择项目负责人',
            filterable: true,
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          style: { width: '100%' }
        },
        {
          name: '绿地面积(m²)',
          prop: 'greenArea',
          attrConfig: { placeholder: '请输入绿地面积(m²)' }
        },
        {
          name: '项目状态',
          prop: 'status',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'select',
          selectParams: {
            codes: ['ecp-admin.sceneProject.status']
          },
          attrConfig: {
            placeholder: '请选择项目状态',
            options: []
          },
          dataProp: {
            keyProp: 'ecp-admin.sceneProject.status',
            nameProp: 'label',
            codeProp: 'value'
          },
          style: { width: '100%' }
        },
        {
          name: '联系方式',
          prop: 'mobilePhone',
          attrConfig: { placeholder: '请输入联系方式' }
        }
        // {
        //   name: '项目图片',
        //   prop: 'imgs',
        //   componentType: 'AddImg',
        //   style: { width: '100%' }
        // },
        // {
        //   name: '项目介绍',
        //   prop: 'proRemark',
        //   componentType: 'WangEditor',
        // }
      ]
    }
  },
  computed: {
    rules() {
      return {
        projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        landArea: [{ required: true, message: '请输入总用地面积', trigger: 'blur' }],
        floorArea: [{ required: true, message: '请输入总建筑面积', trigger: 'blur' }],
        greenArea: [{ required: true, message: '请输入绿地面积', trigger: 'blur' }],
        status: [{ required: true, message: '请选择项目状态', trigger: 'blur' }],
        proRemark: [{ required: false, trigger: 'blur', validator: this.proRemarkValidate }]
      }
    }
  },
  watch: {
    popData: {
      handler(data) {
        this.isAdd = !data.id
        this.formList.forEach((e) => {
          this.$set(this.formData, e.prop, data[e.prop])
        })
        this.$set(this.formData, 'id', data.id)
        if (data.imageList?.length > 0) {
          this.fileList = data.imageList.map(item => {
            return {
              url: item
            }
          })
        } else {
          this.fileList = []
        }
        if (data.backgroundImg != null) {
          this.backgroundList = [{ url: data.backgroundImg }]
        }
        this.formData.proRemark = data.proRemark
      },
      deep: true,
      immediate: true
    },
    confirm() {
      const params = {
        ...(this.formData || {})
      }
      this.submit(params)
    }
  },
  methods: {
    handleChange(file, fileList) {
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过5MB!')
        fileList.pop();
        return false;
      }
      this.fileList = fileList
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    handleBackgroundChange(file, fileList) {
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过5MB!')
        fileList.pop();
        return false;
      }
      this.backgroundList = fileList
    },
    handleBackgroundRemove(file, fileList) {
      this.backgroundList = fileList
    },
    proRemarkValidate(rule, value, callback) {
      if (this.fileList.length > 0 && this.formData.proRemark?.length > 50) {
        callback('项目介绍不超过50字')
        return
      } else if (this.formData.proRemark?.length > 200) {
        callback('项目介绍不超过200字')
        return
      }
      callback()
    },
    editorChange(value) {
      this.formData.proRemark = value
      this.$refs.form.validateField(['proRemark'], (errorMessage) => {
      })
    },
    /**
     * change事件
     */
    handlerSelectData(config) {
      const Ref = this.$refs[config.prop]
      if (Ref && config.isClosePop) {
        Ref.dropDownVisible = false
      }
    },
    /**
     * 提交
     */
    submit(params) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.fileList.length > 0) {
            const files = []
            for (const item of this.fileList) {
              if (item.raw) {
                const formData = new FormData()
                formData.append('file', item.raw)
                const urlRes = await this.$api.fileManage.baseUploadData(
                  '/energy-carbon/grass-file/file/upload',
                  formData
                )
                files.push(urlRes.data)
              } else {
                files.push(item.url)
              }
            }
            params.proImgs = JSON.stringify(files)
          } else {
            params.proImgs = null
          }
          params.proRemark = this.formData.proRemark
          if (this.backgroundList.length > 0) {
            const fileInfo = this.backgroundList[0]
            if (fileInfo.raw) {
              const formData = new FormData()
              formData.append('file', fileInfo.raw)
              const urlRes = await this.$api.fileManage.baseUploadData(
                '/energy-carbon/grass-file/file/upload',
                formData
              )
              params.backgroundImg = urlRes.data
            } else {
              params.backgroundImg = fileInfo.url || ''
            }
          }
          const res = await this.$api.sceneProject[this.isAdd ? 'add' : 'update'](params)
          if (Number(res.code) === 1000) {
            this.$message.success(`${this.isAdd ? '新增' : '编辑'}成功！`)
            this.$emit('onFinish', 'scene-project-add')
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.scene-project-box {
  color: #333;
  padding: 0 20px;

  ::v-deep .el-form {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .el-form-item {
      //width: calc(50% - 10px);

      &.width100p {
        width: 100%;
      }

      .el-form-item__label {
        color: #666;
        font-size: 14px;
      }

      &.form-sub-title {
        width: 100%;

        .el-form-item__label {
          display: flex;
          align-items: center;
          justify-content: flex-start;
          font-weight: bold;
          color: #333;
          font-size: 16px;
          line-height: 1;

          &::before {
            content: '';
            display: inline-block;
            width: 4px;
            height: 15px;
            background-color: #00858d;
            margin-right: 5px;
          }
        }
      }
    }

    .el-select,
    .el-cascader {
      width: 100%;
    }
  }
}
</style>
